<?php
namespace Operator\Model;

class IndexModel extends BaseModel
{
    protected $tableName = 'line_orders as l';
    /**
     * 按天的饼状营业额
     */
    public function dayData()
    {
        $start_time = I('day') ? strtotime(I('day')) : strtotime(date('Y-m-d', time()));
        $end_time   = $start_time + 86399; //23点59分59秒
        $conf       = [
            'closing_time'        => ['between', [$start_time, $end_time]],
            'operator_id'         => session('operator_user.operator_id'),
            'order_status'        => 3,
            'closing_total_money' => ['gt', 0],
            // 'order_status' =>  3,
        ];

        //订单数据
        $m      = M('public_group as g');
        $result = $m
            ->field('sum(need_pay),closing_total_money')
            ->join('__LINE_ORDERS__ as l on g.group_id = l.group_id')
            ->where($conf)
            ->group('g.group_id')
            ->select();
        $income = [];
        foreach ($result as $k => $v) {
            $income['sum(need_pay)'] += $v['sum(need_pay)'];
            $income['closing_total_money'] += $v['closing_total_money'];
        }
        $income['sum(need_pay)']       = round($income['sum(need_pay)'], 2);
        $income['closing_total_money'] = round($income['closing_total_money'], 2);
        $income['profit']              = round($income['sum(need_pay)'] - $income['closing_total_money'], 2);

        //订单总数
        $conf['order_status'] = ['in', '1,3'];
        $order['total']       = $m
            ->join('__LINE_ORDERS__ as l on g.group_id = l.group_id')
            ->where($conf)
            ->getField('count(*)');

        //未处理订单
        $conf['order_status'] = 1;
        $order['wait']        = $m
            ->join('__LINE_ORDERS__ as l on g.group_id = l.group_id')
            ->where($conf)
            ->getField('count(*)');
        $order['deal'] = $order['total'] - $order['wait'];
        return array_merge($order, $income);
    }

    /**
     * 月订单数据统计
     * @return [type] [description]
     */
    public function monthDate()
    {
        $time       = I('month') ? I('month') : date('Y-m', time());
        $start_time = strtotime($time . '-01');
        $s_date     = date('Y-m-d', $start_time);
        $end_time   = strtotime("$s_date +1 month") - 1;
        $conf       = [
            'closing_time'        => ['between', [$start_time, $end_time]],
            'order_status'        => 3,
            'closing_total_money' => ['gt', 0],
        ];
        $conf['l.operator_id'] = session('operator_user.operator_id');

        $result = M('public_group as g')
            ->field("FROM_UNIXTIME(closing_time,'%Y-%m-%d') as day,count(*) as count,sum(need_pay) as pay,closing_total_money as need")
            ->join('__LINE_ORDERS__ as l on g.group_id = l.group_id')
            ->where($conf)
            ->group('g.group_id')
            ->order('order_id asc')
            ->select();
        // $res     = $this->changeIndex($res);
        $res = [];
        foreach ($result as $k => $v) {
            if (isset($res[$v['day']])) {
                $res[$v['day']]['count'] += $v['count'];
                $res[$v['day']]['pay'] += $v['pay'];
                $res[$v['day']]['need'] += $v['need'];
            } else {
                $res[$v['day']]['count'] = $v['count'];
                $res[$v['day']]['pay']   = $v['pay'];
                $res[$v['day']]['need']  = $v['need'];
            }
        }

        $end_day = date('d', strtotime("{$s_date} +1 month -1 day")); //获取本月最后一天
        for ($i = 1; $i <= $end_day; $i++) {
            $key = $time . '-' . str_pad($i, 2, 0, STR_PAD_LEFT);
            if (!isset($res[$key])) {
                $res[$key]['count'] = 0;
                $res[$key]['pay']   = 0;
                $res[$key]['need']  = 0;
            }
            $order['profit'][]     = round($res[$key]['pay'] - $res[$key]['need'], 2);
            $order['endNeedPay'][] = round($res[$key]['pay'], 2);
            $order['orderNum'][]   = (int) $res[$key]['count'];
            $order['conf'][]       = $i . '号';
        }
        $order['profit']     = "'" . json_encode($order['profit']) . "'";
        $order['endNeedPay'] = "'" . json_encode($order['endNeedPay']) . "'";
        $order['orderNum']   = "'" . json_encode($order['orderNum']) . "'";
        $order['conf']       = "'" . json_encode($order['conf']) . "'";
        return $order;
    }

    public function yearsDate()
    {
        $time       = I('years') ? I('years') : date('Y', time());
        $start_time = strtotime($time . '-01-01');
        $s_date     = date('Y-m-d', $start_time);
        $end_time   = strtotime("$s_date +1 year") - 1;

        $conf = [
            'closing_time'        => ['between', [$start_time, $end_time]],
            'order_status'        => 3,
            'closing_total_money' => ['gt', 0],
        ];
        $conf['l.operator_id'] = session('operator_user.operator_id');

        $result = M('public_group as g')
            ->field("FROM_UNIXTIME(closing_time,'%Y-%m') as month,count(*) as count,sum(need_pay) as pay,closing_total_money as need")
            ->join('__LINE_ORDERS__ as l on g.group_id = l.group_id')
            ->where($conf)
            ->group('g.group_id')
            ->order('order_id asc')
            ->select();
        $res = [];
        // $res = $this->changeIndex($res);

        foreach ($result as $k => $v) {
            if (isset($res[$v['month']])) {
                $res[$v['month']]['count'] += $v['count'];
                $res[$v['month']]['pay'] += $v['pay'];
                $res[$v['month']]['need'] += $v['need'];
            } else {
                $res[$v['month']]['count'] = $v['count'];
                $res[$v['month']]['pay']   = $v['pay'];
                $res[$v['month']]['need']  = $v['need'];
            }
        }

        for ($i = 1; $i <= 12; $i++) {
            $key = $time . '-' . str_pad($i, 2, 0, STR_PAD_LEFT);
            if (!isset($res[$key])) {
                $res[$key]['count'] = 0;
                $res[$key]['pay']   = 0;
                $res[$key]['need']  = 0;
            }
            $order['profit'][]     = round($res[$key]['pay'] - $res[$key]['need'], 2);
            $order['endNeedPay'][] = round($res[$key]['pay'], 2);
            $order['orderNum'][]   = (int) $res[$key]['count'];
            $order['conf'][]       = $i . '月';
        }
        $order['profit']     = "'" . json_encode($order['profit']) . "'";
        $order['endNeedPay'] = "'" . json_encode($order['endNeedPay']) . "'";
        $order['orderNum']   = "'" . json_encode($order['orderNum']) . "'";
        $order['conf']       = "'" . json_encode($order['conf']) . "'";
        return $order;
    }

    /**
     * 订单详情
     * @return [$data] [订单详情数组]
     */
    public function orderDetail()
    {
        $data = [];
        //订单信息
        $data['order'] = M('line_orders l')
            ->field('l.*,o.line_name,g.group_num')
            ->join('LEFT JOIN __PUBLIC_LINE__ o on l.line_id = o.line_id')
            ->join('LEFT JOIN __PUBLIC_GROUP__ g on l.group_id = g.group_id')
            ->where(['l.order_id' => I('order_id')])
            ->find();
        //毛利
        $data['order']['profit'] = $data['order']['operator_cost'] - $data['order']['need_pay'];

        //发票信息
        $data['receipt'] = M('public_receipt')
            ->where(['order_id' => $data['order']['order_id']])
            ->find();

        //游客信息
        $data['tourism'] = M('public_tourists')
            ->where(['order_id' => $data['order']['order_id']])
            ->select();

        //订单联系人
        foreach ($data['tourism'] as $v) {
            if ($v['is_contact'] == 1) {
                $data['contact']['name']  = $v['tourists_name'];
                $data['contact']['phone'] = $v['tourists_phone'];
                break;
            }
        }
        switch ($data['order']['order_status']) {
            case -6:
                $data['order']['order_status_content'] = '取消';
                break;

            case -5:
                $data['order']['order_status_content'] = '已退款';
                break;

            case -4:
                $data['order']['order_status_content'] = '拒绝退款';
                break;

            case -3:
                $data['order']['order_status_content'] = '退款审核中';
                break;

            case -2:
                $data['order']['order_status_content'] = '审核不通过';
                break;

            case -1:
                $data['order']['order_status_content'] = '未支付';
                break;

            case 1:
                $data['order']['order_status_content'] = '待审核';
                break;

            case 2:
                $data['order']['order_status_content'] = '审核中';
                break;

            case 3:
                $data['order']['order_status_content'] = '已审核';
                if ($data['order']['is_refund'] == 1) {
                    $data['order']['order_status_content'] = '拒绝退款';
                }

                break;
        }

        return $data;
    }

    /**
     * 待审核的单品供应商商家列表
     */
    public function waitAuditUnitShop($where)
    {
        $count = M('public_single_supplier')
            ->where($where)
            ->count();
        // 分页
        $Page = new \Think\Page($count, 25);
        $show = $Page->show();
        // 查询
        $list = M('public_single_supplier')
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('supplier_id desc')
            ->select();

        return ['list' => $list, 'show' => $show];
    }

    public function changeSupplierStatus($data)
    {
        $res = M('public_single_supplier')->where(array('supplier_id' => $data['supplier_id']))->setField(array('status' => $data['status']));
        if ($res !== false) {
            return ['status' => 1, 'msg' => '操作成功!'];
        }
        return ['status' => 0, 'msg' => '操作失败!'];
    }

    /**
     * 待审核产品列表
     */
    public function waitAuditUnitGoods($admin_id)
    {

        //酒店供应商待审核的产品列表
        $hotelList = M('public_single_room_price as p')
            ->join("__PUBLIC_SINGLE_ROOM__ as r on r.room_id=p.room_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.room_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.star_level,r.room_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id' => $admin_id, 'p.is_review' => -1))
            ->order('p.room_priceId desc')
            ->limit(10)
            ->select();
        //保险供应商
        $insureList = M('public_single_insure_price as p')
            ->join("__PUBLIC_SINGLE_INSURE__ as r on r.insure_id=p.insure_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.insure_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.insure_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id' => $admin_id, 'p.is_review' => -1))
            ->order('p.insure_priceId desc')
            ->limit(10)
            ->select();
        //景区供应商
        $scenicList = M('public_single_scenic_price as p')
            ->join("__PUBLIC_SINGLE_SCENIC__ as r on r.scenic_id=p.scenic_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.scenic_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.scenic_name,r.scenic_level,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id' => $admin_id, 'p.is_review' => -1))
            ->order('p.scenic_priceId desc')
            ->limit(10)
            ->select();
        //交通供应商
        $trafficList = M('public_single_traffic_price as p')
            ->join("__PUBLIC_SINGLE_TRAFFIC__ as r on r.traffic_id=p.traffic_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("__PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.traffic_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.traffic_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id' => $admin_id, 'p.is_review' => -1))
            ->order('p.traffic_priceId desc')
            ->limit(10)
            ->select();

        return ['hotelList' => $hotelList, 'insureList' => $insureList, 'scenicList' => $scenicList, 'trafficList' => $trafficList];

    }

    public function years()
    {
        $year = date('Y', time()) - 24;
        $data = [];
        for ($i = 0; $i < 50; $i++) {
            $data[] = $year++;
        }
        return $data;
    }


    /**
     * 待审核产品列表
     */
    public function auditProductList(){

        $admin_id=session('operator_user.pid')==0?session('operator_user.operator_id'):session('operator_user.pid');
        //酒店供应商待审核的产品列表
        $hotelList=M('public_single_room_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_ROOM__ as r on r.room_id=p.room_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.room_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.star_level,r.room_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id'=>$admin_id,'p.is_review'=>-1,'s.supplier_flag'=>1,'p.is_del'=>1))
            ->order('p.room_priceId desc')
            ->limit(10)
            ->select();
        //保险供应商
        $insureList=M('public_single_insure_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_INSURE__ as r on r.insure_id=p.insure_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.insure_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.insure_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id'=>$admin_id,'p.is_review'=>-1,'s.supplier_flag'=>1,'p.is_del'=>1))
            ->order('p.insure_priceId desc')
            ->limit(10)
            ->select();
        //景区供应商
        $scenicList=M('public_single_scenic_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_SCENIC__ as r on r.scenic_id=p.scenic_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.scenic_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.scenic_name,r.scenic_level,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id'=>$admin_id,'p.is_review'=>-1,'s.supplier_flag'=>1,'p.is_del'=>1))
            ->order('p.scenic_priceId desc')
            ->limit(10)
            ->select();

        //交通供应商
        $trafficList=M('public_single_traffic_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_TRAFFIC__ as r on r.traffic_id=p.traffic_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.traffic_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.traffic_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_operator_id'=>$admin_id,'p.is_review'=>-1,'s.supplier_flag'=>1,'p.is_del'=>1))
            ->order('p.traffic_priceId desc')
            ->limit(10)
            ->select();

        return ['hotelList'=>$hotelList,'insureList'=>$insureList,'scenicList'=>$scenicList,'trafficList'=>$trafficList];

    }


    //待审核的单品供应商列表
    public  function  auditSingleSupplier(){
        $admin_id=session('operator_user.pid')==0?session('operator_user.operator_id'):session('operator_user.pid');
        $list=M('public_single_supplier')->where(['admin_operator_id'=>$admin_id,'status'=>-1,'supplier_flag'=>1])->order('supplier_id desc')->limit(10)->select();

        foreach ($list as $k=>$v){
            $list[$k]['start_time']=date('Y-m-d',$v['start_time']);
            $list[$k]['end_time']=date('Y-m-d',$v['end_time']);
            $list[$k]['typeName']=self::supplierType($v['type']);
            $list[$k]['city']=self::getCityName($v['country']).self::getCityName($v['province']).self::getCityName($v['city']).self::getCityName($v['area']);
        }
        return $list;
    }


    //城市名称
    private function getCityName($cityId){
        return M('areas')->where(array('areaId'=>$cityId))->getField('areaName');
    }
    //供应商类型
    private  function supplierType($type=0){
        //交通1、酒店2、保险3、景区
        $typeName='';
        switch ($type){
            case 1:$typeName='交通';break;
            case 2:$typeName='酒店';break;
            case 3:$typeName='保险';break;
            case 4:$typeName='景区';break;
        }
        return $typeName;
    }


    /**
     * 线路列表
     */
    public  function  lineList(){
        $admin_id=session('operator_user.pid')==0?session('operator_user.operator_id'):session('operator_user.pid');
        $where['l.operator_id']=$admin_id;
        $where['l.line_status']=0;
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list=M('public_line as l')
            ->join('LEFT JOIN __AREAS__ as a on a.areaId=l.origin_id')
            ->join('LEFT JOIN __OPERATOR__ as s on l.verifier_id=s.operator_id')
            ->join('LEFT JOIN __OPERATOR_LINE_SUPPLIER__ as su on su.supplier_id=l.supplier_id')
            ->field('l.travel_days,l.source_type,l.group_num,l.till_day,l.adult_money,l.child_money,l.oldman_money,l.line_id,l.line_name,l.origin_id,l.line_sn,l.create_time,a.areaName,l.line_status,s.operator_name,su.supplier_name')
            ->order('l.line_id desc')
            ->where($where)
            ->limit(10)
            ->select();
        return $list;
    }

    public function  cooperationList(){
        $admin_id=session('operator_user.pid')==0?session('operator_user.operator_id'):session('operator_user.pid');
        $where['partner_status']=0;
        $where['p.operator_id']=$admin_id;
        $list=M('line_operator as p')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on l.line_id=p.line_id')
            ->join('LEFT JOIN __PUBLIC_LINE__ as ll on ll.line_id=p.new_line_id')
            ->join('LEFT JOIN __AREAS__ as a on a.areaId=l.origin_id')
            ->join('LEFT JOIN __OPERATOR_LINE_SUPPLIER__ as su on su.supplier_id=l.supplier_id')
            ->field('p.line_id,p.new_line_id,ll.line_status,p.partner_id,l.supplier_id,l.group_num,l.till_day,l.travel_days,l.adult_money,l.child_money,l.oldman_money,l.line_id,l.line_name,l.origin_id,l.line_sn,l.create_time,a.areaName,su.supplier_name,p.partner_status,p.create_time')
            ->order('p.partner_id desc')
            ->where($where)
            ->limit(10)
            ->group('l.line_id')
            ->select();
        return $list;
    }


    //待审核订单

    public  function  auditOrderList(){
        $m     = D('SaleManger');
        $admin_id=session('operator_user.pid')==0?session('operator_user.operator_id'):session('operator_user.pid');
        $where['lo.operator_id'] =$admin_id;
        $list=$m->orderList($where, -1);
        return $list['list'];
    }

    //待结算
    public function closingList(){
        $admin_id=session('operator_user.pid')==0?session('operator_user.operator_id'):session('operator_user.pid');
        $where['o.operator_id'] = $admin_id;
        $where['order_status']=1;
        $settlementInfo = D('Finance')->getSettlementList($where);
        return $settlementInfo['list'];
    }



}
